<!-- m_cateogry.ftl 存货分类表 -->
var MCateogry = {
    u: '/mCateogry'
    , uList: '/mCateogry/list'
    , uEdit: '/mCateogry/edit'
    , uDel: '/mCateogry/delete'
    , uMSku: '/mCateogry/msku',
    dgType:undefined,
    isAdd:undefined,
    winThat:undefined,
    win: undefined,
    tempThat: undefined,
    newWindow :undefined,
};

MCateogry.dg = function () {
    var grid = new $yd.TreeGrid(this.dtable);
    grid.onDblClickRow = function (row) {
        MCateogry._edit(row['id']);
    };
    grid.onClickRow = function (row) {
        MCateogry.loadLinkedMSku(row.id);
    };
    grid.url = MCateogry.uList;
    // grid.singleSelect = true;
    grid.columns = [[
        {field: 'id', checkbox: true},
        {field: 'pid', title: '父节点', hidden: true},
        {field: 'category_type', title: '分类级别类型', hidden: true}
        , {field: 'name', title: '分类名称', width: 80}
        , {field: 'code', title: '编码', width: 80}
        , {
            field: 'status', title: '状态', width: 50, formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-success">启用</label>';
                } else if (value == 1){
                    return '<label class="label label-default">禁用</label>';
                }
            }
        }
        , {field: 'ctime', title: '创建时间', width: 80}
    ]];
    // grid.onLoadSuccess = function () {
    //     MCateogry.dtable.parent().find("div .datagrid-header-check").children("input[type=\"checkbox\"]").eq(0).attr("style", "display:none;");
    // };
    grid.loadGrid();
};
MCateogry.dg.getOne = function () {
    var sels = MCateogry.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
MCateogry.dg.getSels = function () {
    return MCateogry.dtable.treegrid('getSelections');
};
// 处理按钮
MCateogry.btn = function () {
    var sb = new $yd.SearchBtn($(MCateogry.obtn));
    // sb.create('categorySku', '关联规格', MCateogry.categorySku);
    sb.create('save green', '同步天天爱车分类', MCateogry.synchronization);
    sb.create('remove', '删除(Delete)', MCateogry.remove);
    sb.create('refresh', '刷新(F2)', MCateogry.reset);
    sb.create('edit', '编辑(Shift+E)', MCateogry.edit);
    sb.create('plus', '新增(Shift+N)', MCateogry.plus);

};
// 关联规格
/*
MCateogry.categorySku = function () {
    var sel = MCateogry.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一个二级分类');
        return;
    }
    if (sel && sel['pid'] == 0) {
        $yd.alert("请选择具体的二级分类");
        return false;
    }
    $yd.confirm(function () {
        var mskuSels = MCateogry.getMSkuSels();
        console.log("mskuSels:" + JSON.stringify(mskuSels));
        $yd.post("/mCateogry/updateCSku?cateogryId="+ sel['id'],JSON.stringify(mskuSels), function () {

        });
        
    });
}*/
//同步天天爱车分类
MCateogry.synchronization = function () {
    $yd.confirm(function () {
        // $.get("/mCateogry/synchronization", function (data) {
        //     $yd.alert(data.message);
        // });
        $.ajax({
            type: 'get',
            url: "/mCateogry/synchronization",

            beforeSend: function () {
                $.messager.progress({
                    title: '提示',
                    msg: '同步中，请稍候……',
                    text: ''
                });
            },
            complete: function () {
                $.messager.progress('close');
            },
            success: function (data) {
                $yd.alert(data.message);
            }
        });

    });
    MCateogry.reset();
}
//删除
MCateogry.remove = function () {
    var sels = MCateogry.dg.getSels();
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    $yd.confirm(function () {
        var ids = [];
        $.each(sels, function (i, n) {
            ids.push(n['id']);
        });
        $yd.post(MCateogry.uDel, {ids: ids}, function () {
            MCateogry.refresh();
        });
    })
};
//重置
MCateogry.reset = function () {
    $(".search-form").form('clear');
    $('#mCateogry_table').datagrid('unselectAll');
    MCateogry.search();
};
//
MCateogry.edit = function () {
    var sel = MCateogry.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    MCateogry._edit(sel['id'],sel['pid'])
};
MCateogry._edit = function (id,pid) {
    MCateogry.dgType = "house";
    var dg = $yd.win2.create('编辑', MCateogry.uEdit + '?id=' + id);
    dg.open(function (that, $win) {
        MCateogry.win = $win;
        MCateogry.winThat = that;
            $yd.get(MCateogry.u + "/" + id, function (data) {
                $win.find('form').form('load', data);
            })
        }, function () {
        MCateogry.save();
        }, function () {
        MCateogry.closeDg(1);
        }
    );
};
//新增
MCateogry.plus = function () {
    var sel = MCateogry.dg.getOne();
    if (sel && sel['category_type'] == 3) {
        $yd.alert("请选择上级目录");
        return false;
    }
    var href = MCateogry.uEdit;
    if (sel) href += '?pid=' + sel['id'] + '&name=' + sel['name'];

    MCateogry.dgType = "house";
    var dg = $yd.win2.create('新增', href);
    dg.open(function (that, $win) {
        MCateogry.win = $win;
        MCateogry.winThat = that;
        }, function () {
        MCateogry.save();
        }, function () {
        MCateogry.closeDg(1);
        } , function () {
        MCateogry.saveNext();
        }
    );
};

MCateogry.save = function () {
    $yd.form.create(MCateogry.win.find('form')).url(MCateogry.u).submit(function () {
        MCateogry.refresh();
        MCateogry.closeDg(0);
    });
};
MCateogry.saveNext = function () {
    $yd.form.create(MCateogry.win.find('form')).url(MCateogry.u).submit(function () {
        MCateogry.closeDg(0);
        MCateogry.plus();
    });
};
//
MCateogry.refresh = function () {
    $('#mCateogry_table').datagrid('unselectAll');
    MCateogry.dtable.treegrid('reload');
};
//搜索
MCateogry.search = function () {
    MCateogry.dtable.treegrid('load', MCateogry.sform.serializeObject());
    MCateogry.loadMSku();

};

// 选中属于当前分类的规格
MCateogry.loadLinkedMSku = function (id) {
    MCateogry.isMSku = true;
    MCateogry.mSku.datalist('uncheckAll');
    $yd.get(MCateogry.uMSku, {categoryId: id}, function (data) {
        $.each(data, function (i, n) {
            MCateogry.mSku.datalist('selectRecord', n['sku_id']);
        });
        MCateogry.isMSku = false;
    })
};
MCateogry.getMSkuSels = function () {
    return $('#mSku').datagrid('getSelections');
};
// 加载规格
MCateogry.loadMSku = function () {
    MCateogry.mSku = $('#mSku');
    var dl = new $yd.datalist(MCateogry.mSku);
    dl.onSelect = function (index, row) {
        select(row.id, 0)
    };
    dl.onUnselect = function (index, row) {
        select(row.id, -1)
    };
    dl.load('/mSku/select');

    function select(skuId, id) {
        if (!MCateogry.isMSku) {

            var sels = MCateogry.dg.getSels();
            if (sels.length > 0) {
                var cSku = [];
                $.each(sels, function (i, n) {
                    if (n.category_type !=3) {
                        $yd.alert("请选择具体的三级分类");
                        return false;
                    }
                    cSku.push({skuId: skuId, id: id, categoryId: n.id});
                });
                $yd.post(MCateogry.uMSku, JSON.stringify(cSku));
            } else {
                $yd.alert("未选择分类");
            }
        }
    }
};
MCateogry.closeDg = function (closeEd) {
    if(closeEd == 0) {
        MCateogry.winThat.close();
    }

    MCateogry.dgType = undefined;
    MCateogry.winThat = undefined;
    MCateogry.win = undefined;
    MCateogry.isAdd = undefined;
};
MCateogry.init = function () {
    document.onkeyup = MCateogry.keyUp;
    //先获取焦点再失去焦点，否则打开页面后若不点击页面，快捷键无效
    $("#name").next().find(".textbox-text").focus()
    $("#name").next().find(".textbox-text").blur()
}
MCateogry.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if($yd.isForbidCutKey == 1) {
        return;
    }
    if($yd.isEmpty(MCateogry.dgType)) { //未弹框
        if (e.shiftKey && e.keyCode == 78) { //Shift+N
            MCateogry.plus();
        }
        if (e.shiftKey && e.keyCode == 69) { //Shift+E
            MCateogry.edit();
        }
        if(e.keyCode == 113) {//F2
            MCateogry.refresh();
        }
        if(e.keyCode == 46) {//DEL
            MCateogry.remove();
        }
        if(e.keyCode == 13) {
            MCateogry.search();
        }
    } else{ //弹框
        if(e.keyCode == 27) {//ESC
            MCateogry.closeDg(0);
        }
        if(e.keyCode == 13) {//Enter
            if(e.ctrlKey) {//Ctrl+Enter
                MCateogry.saveNext();
            } else {
                MCateogry.save();
            }
        }
    }
};

$(function () {
    MCateogry.sform = $('#mCateogry_form');
    MCateogry.eform = $('#mSku');
    MCateogry.dtable = $('#mCateogry_table');
    MCateogry.obtn = '#mCateogry_btn';

    MCateogry.dg(); // 数据表格
    MCateogry.btn(); // 初始化按钮
    MCateogry.init(); //初始化快捷键
    $yd.bindEnter(MCateogry.search);

    MCateogry.loadMSku();

});
var btn1 = document.getElementById("searchButton");
btn1.addEventListener("click", function() {
    $('#mCateogry_table').datagrid('unselectAll');
    MCateogry.search();
});


